ActiveAdmin.register CampOrder do
  menu label: '训练营', parent: '订单'

  actions :index
  filter :member_mobile, as: :string, label: '手机号'
  filter :appointment_camp_name, as: :string, label: '训练营'
  filter :order_no, label: '订单号'
  filter :total, label: '金额'
  filter :created_at, label: '下单时间'


  index do
    column :order_no
    column :name
    column :mobile
    column :product
    column :total
    column :coupon
    column :pay_amount
    column :created_at
    column :status_i18n
  end

  controller do
    def scoped_collection
      CampOrder.joins(:member, :appointment).left_joins(:running_account).select(
          :id,
          :order_no,
          'members.name as name',
          'members.mobile as mobile',
          "camp_appointments.camp_name as product",
          :total,
          :coupon,
          :pay_amount,
          :pay_type,
          :status,
          :created_at,
          'transactions.created_at as paid_at'
      )
    end

    def index
      if params[:format].eql?("csv") || params[:format].eql?("xls")
        sql = CampOrder.ransack(params[:q]).result.to_sql
        filter = sql.split("WHERE")[1]
        csv = CSV.generate(headers: true) do |row|
          row << %w{订单号 会员 手机号 产品 订单金额 优惠金额 实付金额 付款方式 下单时间 支付时间 订单状态}
          CampOrder.joins(:member, :appointment).left_joins(:running_account).where(filter).pluck(
              Arel.sql("camp_orders.order_no, members.name, members.mobile, camp_orders.total, camp_orders.coupon,
              camp_orders.pay_amount, camp_orders.pay_type, to_char(camp_orders.created_at,'YYYY-MM-DD HH24:MI:SS'), to_char(transactions.created_at,'YYYY-MM-DD HH24:MI:SS'),
              '{\"-2\": \"已删除\",\"-1\": \"已取消\",\"0\": \"待付款\",\"1\": \"已付款\",\"2\": \"已退款\"}'::jsonb -> camp_orders.status::text")
          ).each {|data| row << data}
        end
        send_data("\uFEFF" + csv, type: Mime[:csv], disposition: "attachment; filename=预约信息-#{Time.current.to_i}.csv")
      else
        index!
      end
    end
  end
end
